import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const routes = [
  {
    // 登录
    path: '/',
    name: 'login',
    component: () => import('@/views/login/index.vue')
  },
  {
    // 江苏演示登录
    path: '/loginsJs',
    name: 'loginsJs',
    component: () => import('@/views/LoginJs.vue')
    // children: []
  },
  {
    // 首页
    path: '/index',
    name: 'index',
    component: () => import('@/layout/default.vue')
    // children: []
  },
  {
    // 首页
    path: '/index/*',
    name: 'index',
    component: () => import('@/layout/default.vue')
  },
  {
    path: '/404',
    name: '404',
    component: () => import('@/views/404.vue')
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

router.beforeEach((to, from, next) => {
  const vuex = JSON.parse(sessionStorage.getItem('vuex'))
  // 不需要在请求返回后统一处理的URL
  // 包含詳情页面
  const EXCLUDE_URLS = [
    '/',
    '/404',
    '/index',
    '/loginsJs',
    '/index/xtgl/creatgzkj',
    '/index/sjzy/sjzyManageEdit',
    '/index/sjzy/sjzyDetail',
    '/index/jkwg/jkfwxq',
    '/index/sjzl/jcjgxq',
    '/index/sjzl/xjbjrw',
    '/index/sjzl/gzsj',
    '/index/sjzl/jcjg',
    '/index/sjzl/gzgl',
    '/index/sjts/sjtsgc/kbts',
    '/index/sjts/sjtsgc/wjts',
    '/index/sjts/sjtsgc/xxts',
    '/index/sjts/rzcx/kbrz',
    '/index/sjts/rzcx/wjrz',
    '/index/sjts/rzcx/xxrz',
    '/index/sjgl/sjy',
    '/index/sjgl/sjzd',
    '/index/fjcl/bjpt',
    '/index/sjzy/editor-zcml',
    '/index/sjts/sjtsgc/jkts',
    '/index/jkwg/gzsj',
    '/index/jkwg/xjbjrw',
    '/index/jkwg/jcjgxq',
    '/index/jkwg/jcjg',
    '/index/fjcl/wbbzxq',
    '/index/fjcl/sjjxq',
    '/index/fjcl/regex'
  ]

  if (EXCLUDE_URLS.indexOf(to.path) >= 0) {
    next()
  } else {
    if (!vuex) next('/')
    const gnList = vuex.gnList
    let flag = false
    const recursion = arr => {
      if (arr && arr.length > 0) {
        arr.forEach(item => {
          if (!flag && item.gndz === to.path) {
            flag = true
          } else {
            recursion(item.children)
          }
        })
      }
    }
    recursion(gnList, 'gndz')
    if (flag) {
      next()
    } else {
      next('/404')
    }
  }
})

export default router
